import { defineStore } from 'pinia'
import { apiLogin, apiLogout, apiChangePass } from '@/api/login'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoutes, asyncRoutes, anyRoutes } from '../../router/routes'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'

function filterAsyncRoutes(allAsyncRoutes, permissions) {
  return allAsyncRoutes.filter(route => {
    if(permissions.includes(route.name)) {
      if(route.children && route.children.length > 0) {
        route.children = filterAsyncRoutes(route.children, permissions)
      }
      return true
    }
    return false
  })
}

const useUserStore = defineStore('User', {
  state: () => {
    return {
      viewHeight: document.documentElement.clientHeight - 72,
      userData: {},
      menuRoutes: constantRoutes,
      // 假造一些菜单权限数据
      testRoutes: [
        'index','home',
        'cost', 'costUser','costDevice','costMaterial',
        'stock','stockManage','stockWarning','dataC','dataCollection',
        'device','deviceCode','deviceDeep','deviceFault','deviceRemote','deviceReport',
        'bug','bugNg','bugData','bugPrevent',
        'monitor','monitorProcess','monitorData','monitorDevice','monitorAbnormal',
      ]
    }
  },
  actions: {
    async login(data) {
      // const res = await apiLogin(data)
      // if (res) {

      // this.userData = res.data.user;
      // SET_TOKEN(this.userData)

      // this.menuRoutes = res.data.menus;

      // }
      this.getMenuList()
      return 'ok'
    },
    getMenuList(permissions = this.testRoutes) {
      // 根据用户权限，过滤需要展示的异步路由
      let userAsyncRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), permissions)
      // console.log('user async routes',userAsyncRoutes)
      
      // 拿到所有需要展示的菜单集合
      this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, ...anyRoutes]
      // 目前路由器只引入了常量路由，用户计算完异步路由后，需要动态追加异步路由和任意路由。
      ;[...userAsyncRoutes, ...anyRoutes].forEach(route => {
        router.addRoute(route)
      })
    },
    async logout() {
      return 'ok'
    }
  },
  getters: {},
})

export default useUserStore
